package com.lhyl.front.web.controller;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.lhyl.front.common.SiteUtil;
import com.lhyl.front.common.StringUtils;
import com.lhyl.front.constant.FrontConstant;
import com.lhyl.front.constant.ReportConstant;
import com.lhyl.front.constant.UserConstant;
import com.lhyl.front.model.PageModel;
import com.lhyl.front.web.shiro.model.User;
import com.lhyl.front.web.shiro.service.UserService;
import com.lhyl.front.web.user.service.UserProxyService;

/**
 * 代理管理
 * @author GusonYang
 *
 */
@Controller
public class ProxyController extends BaseController{
  
	@Autowired
	private UserProxyService userProxyService;
	
	@Autowired
	private UserService userService;
	
	
    @RequestMapping("/content/proxy/vip")
    /***
     *  代理中心主页面
     * @param modelMap
     * @return
     * @throws Exception
     */
    public String Info(ModelMap modelMap)  throws Exception {
        return "proxy/vip/vip";
    }
    
    @RequestMapping("/proxy/pagingProxy")
    /***
     *  代理中心分页查询
     * @param modelMap
     * @return
     * @throws Exception
     */
    public void pagingProxy(HttpServletRequest req,HttpServletResponse response,ModelMap modelMap)  throws Exception 
    {
    	User user = super.getLoginUserObject();
    	 try
    	 {
    		Map<String, Object>query = this.buildQueryMap(req);
    	    query.put("uid",user.getId());
    	    PageModel pg = this.reportService.pagingReportResult("pagingProxy", query);
    	    pg.setPageIndex(StringUtils.str2Int(req.getParameter(FrontConstant.PAGE_INDEX)));
    	    this.renderMsg(response, FrontConstant.SUCCESS_CODE, StringUtils.EMPTY, pg.toMap());
    	 }catch (Exception e) 
    	 {
    		this.renderMsg(response, FrontConstant.FAILED_CODE, e.getMessage(), StringUtils.EMPTY);
		}
    }
    
    @RequestMapping("/content/proxy/vip/add")
    /***
     * 跳转到创建代理中心页面 添加会员
     * @param modelMap
     * @return
     * @throws Exception
     */
    public String toCreateProxy(HttpServletRequest req,HttpServletResponse response,ModelMap modelMap)  throws Exception {
    	User user = super.getLoginUserObject();
    	double fanDian = StringUtils.str2Double(this.reportService.queryCmsConf(ReportConstant.DIFFERENCE));
    	modelMap.put("fanDian", user.getFandian()-fanDian/100);//当前用户的返点，添加下属 的代理，会员不能高于当前返点
    	return "proxy/vip/add-vip";
    }
    
    @RequestMapping(value="/proxy/saveProxy",method = RequestMethod.POST)  
    /***
     * 保存会员代理
     * @param modelMap
     * @return
     * @throws Exception
     */
    public void saveProxy(HttpServletRequest req,HttpServletResponse response, @ModelAttribute("user") User user)  throws Exception 
    { 
    	 try
    	 {
    		 User current =super.getLoginUserObject();
    		 int userType = current.getUserType();
    		 String loginName =user.getLoginName();
    		 User check= userService.findByUserName(loginName);
    		 if(check==null)
    		 {
    		 if(userType==UserConstant.USER_PROXY_TYPE)
    		 {
        	 Date date = new Date();
        	 user.setFandian(user.getFandian()/100);
             user.setVirtualAccount(current.getVirtualAccount());
        	 user.setStatus(UserConstant.USER_NORMAL_STATUS) ;
        	 user.setRegisterDate(date);
        	 user.setRegisterAddr(SiteUtil.getIpAddr());
        	 user.setCreateUser(current.getId());
        	 user.setModifyUser(current.getId());
        	 user.setModifyDate(date);
        	 user.setIsOnline(UserConstant.USER_OFF_LINE);
        	// user.setUserPassword(MD5Util.MD5(user.getUserPassword()));//用户密码
        	 user.setCoin(0.00);
        	 user.setFcoin(0.00);
        	 this.userProxyService.createProxy(user);
        	 this.renderMsg(response, FrontConstant.SUCCESS_CODE, "", StringUtils.EMPTY);
    		 return;
    		 }
    		 this.renderMsg(response, FrontConstant.FAILED_CODE, "会员无法创建下级代理，用户。", StringUtils.EMPTY);
    	   }
    	   else
    	   {
    			StringBuilder sb = new StringBuilder();
    			sb.append(loginName).append("已经在平台注册!");
    			this.renderMsg(response, FrontConstant.FAILED_CODE, sb.toString(), StringUtils.EMPTY);
    			return;
    	   }
    	 }catch (Exception e) 
    	 {
    		this.renderMsg(response, FrontConstant.FAILED_CODE, e.getMessage(), StringUtils.EMPTY);
		} 
    }
    
    /***
     * @desc 查询下级代理
     * @param req
     * @param response
     */
    @RequestMapping("/proxy/pagingSubagent")
    public void pagingSubagent(HttpServletRequest req,HttpServletResponse response)throws IOException
    { 
    	 try
    	 { 
    		User user= this.getLoginUserObject();
    		Map<String,Object>query = this.buildQueryMap(req);
    		int uid =StringUtils.str2Int(query.get("uid")+"");
    		query.put("isSelf", (uid==user.getCreateUser())?"Y":"N");
    	    PageModel pg = this.reportService.pagingReportResult("pagingProxy", query);
    	    pg.setPageIndex(StringUtils.str2Int(req.getParameter(FrontConstant.PAGE_INDEX)));
    	    this.renderMsg(response, FrontConstant.SUCCESS_CODE, StringUtils.EMPTY, pg.toMap());
    	 }catch (Exception e) 
    	 {
    		this.renderMsg(response, FrontConstant.FAILED_CODE, e.getMessage(), StringUtils.EMPTY);
		 } 
    } 
    
    
    /***
     * @desc 查看当前下级代理信息
     * @param req
     * @param response
     */
    @RequestMapping(value="/proxy/curProxyInfo")
    public void toUpdateSubProxy(HttpServletRequest req,HttpServletResponse response,ModelMap map)throws IOException,Exception
    {  
    	try
	   	 { 
    	    User user = this.getLoginUserObject();
    		Map<String,Object> result = this.reportService.querySingleResult("queryUserInfo", this.buildQueryMap(req));
    		//result.put("userFandian", user.getFandian());
        	double fanDian = new BigDecimal(this.reportService.queryCmsConf(ReportConstant.DIFFERENCE)).divide(new BigDecimal(100)).doubleValue();
        	result.put("userFandian", user.getFandian()-fanDian);//当前用户的返点，添加下属 的代理，会员不能高于当前返点
        	result.put("userCoin", user.getCoin());
    		this.renderMsg(response, FrontConstant.SUCCESS_CODE, StringUtils.EMPTY, result);
	   	 }catch (Exception e) {
	   		this.renderMsg(response, FrontConstant.FAILED_CODE, e.getMessage(), StringUtils.EMPTY);
		} 
    } 
    
    
    
    /***
     * @desc 修改下级代理信息
     * @param req
     * @param response
     */
    @RequestMapping(value="/proxy/updateSubProxy")
    public void updateSubProxy(HttpServletRequest req,HttpServletResponse response,@ModelAttribute("user")User user)throws IOException,Exception
    {  
    	 try
    	 { 
    		this.userService.updateUser(user);
    	    this.renderMsg(response, FrontConstant.SUCCESS_CODE, StringUtils.EMPTY, StringUtils.EMPTY);
    	 }catch (Exception e) 
    	 {
    		this.renderMsg(response, FrontConstant.FAILED_CODE, e.getMessage(), StringUtils.EMPTY);
		 } 
    } 
    
    
    @RequestMapping(value="/proxy/chargeSubProxy")
    public void chargeSubProxy(HttpServletRequest req,HttpServletResponse response)throws IOException,Exception
    {  
    	 try
    	 { 
    		User p = getLoginUserObject();//获取当前登录用户
       		double coin =StringUtils.str2Double(req.getParameter("coin"));
    		if(p.getCoin()>=coin)
    		{
    		   User user= userService.findByID(StringUtils.str2Int(req.getParameter("id")));
    		   this.userProxyService.chargeSubProxy(user, coin);
    	       this.renderMsg(response, FrontConstant.SUCCESS_CODE, StringUtils.EMPTY, StringUtils.EMPTY);
    		}
    		else
    		{
    			this.renderMsg(response, FrontConstant.FAILED_CODE,"当前用户余额不足，无法充值。", StringUtils.EMPTY);
    		}
    	 }catch (Exception e) 
    	 {
    		this.renderMsg(response, FrontConstant.FAILED_CODE, e.getMessage(), StringUtils.EMPTY);
		 } 
    } 
    
    
    @RequestMapping(value="/proxy/checkLoginName")
    public void checkLoginName(HttpServletRequest req,HttpServletResponse response,ModelMap modelMap)  throws Exception {
            String userName = req.getParameter("userName");
    		User user =  userService.findByUserName(userName);
    		if(user!=null)
    		{
    			StringBuilder sb = new StringBuilder();
    			sb.append(userName).append("已经在平台注册!");
    			this.renderMsg(response, FrontConstant.FAILED_CODE, sb.toString(), StringUtils.EMPTY);
    			return;
    		}
    	   this.renderMsg(response, FrontConstant.SUCCESS_CODE, StringUtils.EMPTY, StringUtils.EMPTY);
    }
    
    
}
